
//
//  LoginViewController.m
//  DaJiang
//
//  Created by sally on 16/10/7.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "LoginViewController.h"
#import "UserModel.h"
#import "FinishInfoViewController.h"
#import "TabOneViewController.h"
#import "TabFourViewController.h"

@interface LoginViewController ()

@property (weak, nonatomic) IBOutlet UIButton *closeBtn;
//第三方登录按钮（需求取消）
@property (weak, nonatomic) IBOutlet UIButton *weixinBtn;
@property (weak, nonatomic) IBOutlet UIButton *qqBtn;
@property (weak, nonatomic) IBOutlet UIButton *weiboBtn;

//登录模块
@property (weak, nonatomic) IBOutlet UIView *loginView;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UITextField *loginPhoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *loginPswTextField;//密码框

//忘记密码模块
@property (weak, nonatomic) IBOutlet UIView *forgetPswView;
@property (weak, nonatomic) IBOutlet UIButton *forgetSendCodeBtn;
@property (weak, nonatomic) IBOutlet UIButton *forgetFinishBtn;
@property (weak, nonatomic) IBOutlet UITextField *forgetPhoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *forgetCodeTextFeild;
@property (weak, nonatomic) IBOutlet UITextField *forgetPswTextField;

//注册模块
@property (weak, nonatomic) IBOutlet UIView *registerView;
@property (weak, nonatomic) IBOutlet UITextField *registerPhoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *registerCodeTextField;
@property (weak, nonatomic) IBOutlet UIButton *registerSendCodeBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UITextField *registerPswTextField;
@property (weak, nonatomic) IBOutlet UIButton *registerReadBtn;

@property (strong, nonatomic) UIImageView *pswRightView;

@end

@implementation LoginViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [self initControl];
}

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
  [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:animated];
  [self.navigationController setNavigationBarHidden:NO animated:YES];
}

#pragma mark 初始化控件
- (void)initControl {
  self.closeBtn.hidden = self.isHiddenBack;

  //密码框右图（三页面共用）
  self.pswRightView = [[UIImageView alloc] init];
  self.pswRightView.size = CGSizeMake(40, 40);
  self.pswRightView.contentMode = UIViewContentModeCenter;
  self.pswRightView.image = [UIImage imageNamed:@"psw_invisible_ic"];
  UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionPswVisible)];
  
  if (self.accountType == AccountType_Login) { //登录
    self.loginView.hidden = NO;
    self.forgetPswView.hidden = YES;
    self.registerView.hidden = YES;
    
    //密码框
    self.loginPswTextField.rightView = self.pswRightView;
    self.loginPswTextField.rightViewMode = UITextFieldViewModeAlways;
    self.loginPswTextField.rightView.userInteractionEnabled = YES;
    [self.loginPswTextField.rightView addGestureRecognizer:tap];
    
    //按钮
    self.loginBtn.layer.cornerRadius = GLargeCornerRadius;
    self.loginBtn.layer.masksToBounds = YES;
  } else if (self.accountType == AccountType_Register) { //注册
    self.loginView.hidden = YES;
    self.forgetPswView.hidden = YES;
    self.registerView.hidden = NO;
    
    //密码框
    self.registerPswTextField.rightView = self.pswRightView;
    self.registerPswTextField.rightViewMode = UITextFieldViewModeAlways;
    self.registerPswTextField.rightView.userInteractionEnabled = YES;
    [self.registerPswTextField.rightView addGestureRecognizer:tap];
    
    //按钮
    self.closeBtn.hidden = YES;
    self.registerSendCodeBtn.layer.cornerRadius = GLargeCornerRadius;
    self.registerSendCodeBtn.layer.masksToBounds = YES;
    self.registerBtn.layer.cornerRadius = GLargeCornerRadius;
    self.registerBtn.layer.masksToBounds = YES;
  } else if (self.accountType == AccountType_ForgetPsw) { //忘记密码
    self.loginView.hidden = YES;
    self.forgetPswView.hidden = NO;
    self.registerView.hidden = YES;
    
    //密码框
    self.forgetPswTextField.rightView = self.pswRightView;
    self.forgetPswTextField.rightViewMode = UITextFieldViewModeAlways;
    self.forgetPswTextField.rightView.userInteractionEnabled = YES;
    [self.forgetPswTextField.rightView addGestureRecognizer:tap];
    
    //按钮
    [self.closeBtn setImage:[UIImage imageNamed:@"account_back_ic"] forState:UIControlStateNormal];
    self.forgetSendCodeBtn.layer.cornerRadius = GLargeCornerRadius;
    self.forgetSendCodeBtn.layer.masksToBounds = YES;
    self.forgetFinishBtn.layer.cornerRadius = GLargeCornerRadius;
    self.forgetFinishBtn.layer.masksToBounds = YES;
  }
  
  //第三方登录按钮设置上图下文（三页面共用）
  [[CommonMethod sharedCommonMethod] setBtnDownTextStyle:self.weixinBtn];
  [[CommonMethod sharedCommonMethod] setBtnDownTextStyle:self.qqBtn];
  [[CommonMethod sharedCommonMethod] setBtnDownTextStyle:self.weiboBtn];
}

#pragma mark - action
#pragma mark 登录页用
- (IBAction)actionOnLogin:(id)sender {
  NSString *phone = self.loginPhoneTextField.text;
  NSString *psw = self.loginPswTextField.text;
  
  if (phone.length < 1) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入手机号码"];
    return;
  }
  if (![OperationManager isMobileNumber:phone]) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入正常格式的联系方式"];
    return;
  }
  if (psw.length < 1) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入密码"];
    return;
  }
  
  MBProgressHUD *hud = [[CommonMethod sharedCommonMethod]createProgressHUDInView:self.view withMessage:@""];
  [UserModel loginWithPhone:phone password:psw completion:^(UserModel *user) {
    if (user) {
      //注册并登录环信
      [self registEaseMob:user];
      
      //缓存用户信息
      user.user_data.phone = phone;//登录接口不返回手机号码，所以需要额外给定
      [[CacheManager shareInstance]cacheLastLoginAccount:user];
      
      //信鸽注册设备
      [OperationManager registXGDevice];
      
      //如果没设置昵称和头像则需要进入“完善资料页”
      if (user.user_data.user_name && user.user_data.user_profile_pic && user.user_data.user_name.length > 0 && user.user_data.user_profile_pic.length > 0) {
        //退出
        [self actionOnClose:nil];
      }else{
        //跳转到“完善资料页面”
        [self gotoFinishInfoVc:YES];
      }
      
    } else {
      NSError *error = [UserModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
    hud.hidden = YES;
  }];
}

- (IBAction)goToRegister:(id)sender {
  LoginViewController *vc = [[LoginViewController alloc] init];
  vc.accountType = AccountType_Register;
  [self presentViewController:vc animated:YES completion:nil];
}

- (IBAction)goToForgetPsw:(id)sender {
  LoginViewController *vc = [[LoginViewController alloc] init];
  vc.accountType = AccountType_ForgetPsw;
  [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark 忘记密码页用
- (IBAction)actionOnFinish:(id)sender {
  NSString *phone = self.forgetPhoneTextField.text;
  NSString *psw = self.forgetPswTextField.text;
  NSString *code = self.forgetCodeTextFeild.text;
  if (phone.length < 1) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入手机号码"];
    return;
  }
  if (![OperationManager isMobileNumber:phone]) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入正常格式的联系方式"];
    return;
  }
  if (code.length < 1) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入验证码"];
    return;
  }
  if (psw.length < 1) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入密码"];
    return;
  }

  MBProgressHUD *hud = [[CommonMethod sharedCommonMethod]createProgressHUDInView:self.view withMessage:@""];
  [UserModel resetPswWithPhone:phone password:psw captcha:code completion:^(BOOL isSucceed) {
    if (isSucceed) {
      [[CommonMethod sharedCommonMethod] showAlertMessage:@"已成功修改密码"];
      [self actionOnClose:nil];
    } else {
      NSError *error = [UserModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
    hud.hidden = YES;
  }];

}

#pragma mark 忘记密码、注册共用
//FIXME: 为什么操作可以共用一个IBAction，控件不可以共用一个IBOutlet
- (IBAction)actionOnSendCode:(id)sender {
  NSString *phone;
  if (self.accountType == AccountType_Register) {
    phone = self.registerPhoneTextField.text;
  } else {
    phone = self.forgetPhoneTextField.text;
  }
  
  if (phone && phone.length > 0 ) {
    if (![OperationManager isMobileNumber:phone]) {
      [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入正常格式的联系方式"];
      return;
    }
    
    MBProgressHUD *hud = [[CommonMethod sharedCommonMethod]createProgressHUDInView:self.view withMessage:@""];
    [UserModel sendCaptchaWithPhone:phone completion:^(BOOL isSucceed) {
      if (isSucceed) {
        [[CommonMethod sharedCommonMethod] showAlertMessage:@"已发送验证码至手机，请查收！"];
      } else {
        NSError *error = [UserModel getLastError];
        [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
      }
      hud.hidden = YES;
    }];
  } else {
    [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"请输入手机号码"];
  }
}

#pragma mark 注册页用
- (IBAction)actionOnRegister:(id)sender {
  NSString *phone = self.registerPhoneTextField.text;
  NSString *code = self.registerCodeTextField.text;
  NSString *psw = self.registerPswTextField.text;
  if (phone.length < 1) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入手机号码"];
    return;
  }
  if (![OperationManager isMobileNumber:phone]) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入正常格式的联系方式"];
    return;
  }
  if (code.length < 1) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入验证码"];
    return;
  }
  if (psw.length < 1) {
    [[CommonMethod sharedCommonMethod]showToastInCenter:self.view withMessage:@"请填入密码"];
    return;
  }

  MBProgressHUD *hud = [[CommonMethod sharedCommonMethod]createProgressHUDInView:self.view withMessage:@""];
  [UserModel registerWithPhone:phone captcha:code password:psw completion:^(UserModel *user) {
    if (user) {
      if (user.user_data.new_user) {
        //注册并登录环信
        [self registEaseMob:user];
        
        //缓存用户信息
        [[CacheManager shareInstance]cacheLastLoginAccount:user];
        
        //信鸽注册设备
        [OperationManager registXGDevice];
        
        //跳转到“完善资料页面”
        [self gotoFinishInfoVc:NO];
        
      }else{
        [[CommonMethod sharedCommonMethod] showAlertMessage:@"您已注册过，请登录！"];
      }
      
    } else {
      NSError *error = [UserModel getLastError];
      [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
    hud.hidden = YES;
  }];

}

- (IBAction)goToLogin:(id)sender {
  [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)actionOnRead:(id)sender {
  self.registerReadBtn.selected = !self.registerReadBtn.isSelected;
}

#pragma mark 三页面共用
#pragma mark 退出
- (IBAction)actionOnClose:(id)sender {
  if (self.accountType == AccountType_Login) { //登录
    //退到首页
    [self dismissViewControllerAnimated:YES completion:nil];
    UINavigationController *currNav = [[CommonMethod sharedCommonMethod]getCurrNavController];
    UIViewController *currVc = [currNav.viewControllers objectAtIndex:0];
    if ([currVc isKindOfClass:[TabOneViewController class]] || [currVc isKindOfClass:[TabFourViewController class]]) {
      [currNav popToRootViewControllerAnimated:YES];
    }else{
      [OperationManager gotoTabOne];
    }
  }else if (self.accountType == AccountType_ForgetPsw) { //忘记密码
    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
  }else{
    [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];
  }
}

#pragma mark - 私有方法
#pragma mark 操作密码可视化控件
- (void)actionPswVisible { //三页面公用
  if (self.loginPswTextField.isSecureTextEntry) {
    self.pswRightView.image = [UIImage imageNamed:@"psw_visible_ic"];
  } else {
    self.pswRightView.image = [UIImage imageNamed:@"psw_invisible_ic"];
  }
  
  if (self.accountType == AccountType_Login) { //登录
    self.loginPswTextField.secureTextEntry = !self.loginPswTextField.isSecureTextEntry;
  } else if (self.accountType == AccountType_Register) { //注册
    self.registerPswTextField.secureTextEntry = !self.registerPswTextField.isSecureTextEntry;
  } else if (self.accountType == AccountType_ForgetPsw) { //忘记密码
    self.forgetPswTextField.secureTextEntry = !self.forgetPswTextField.isSecureTextEntry;
  }
}

#pragma mark 跳转到“完善资料页面”
- (void)gotoFinishInfoVc:(BOOL)isLogin {
  FinishInfoViewController *vc = [[FinishInfoViewController alloc] init];
  vc.isHiddenBack = YES;
  vc.hidesBottomBarWhenPushed = YES;
  [[[CommonMethod sharedCommonMethod]getCurrNavController] pushViewController:vc animated:YES];

  if (isLogin) {
    [self.presentingViewController dismissViewControllerAnimated:NO completion:nil];
  }else{
    [self.presentingViewController.presentingViewController dismissViewControllerAnimated:NO completion:nil];
  }
}

#pragma mark - 环信相关
#pragma mark 注册环信账号
- (void)registEaseMob:(UserModel *)userModel {
  //异步注册账号
  NSString *userAccount = [NSString stringWithFormat:@"%@%ld", HXPrefix , (long)userModel.uid];
  NSString *userPsw = @"111111";//密码固定
  [[EaseMob sharedInstance].chatManager asyncRegisterNewAccount:userAccount password:userPsw  withCompletion: ^(NSString *username, NSString *password, EMError *error) {
    if (!error) {
      NSLog(NSLocalizedString(@"register.success", @"Registered successfully, please log in"));
      [self loginEaseMob:userAccount password:userPsw];
    }else{
      switch (error.errorCode) {
        case EMErrorServerNotReachable:
          NSLog(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
          break;
        case EMErrorServerDuplicatedAccount:
          NSLog(NSLocalizedString(@"register.repeat", @"You registered user already exists!"));
          [self loginEaseMob:userAccount password:userPsw];
          break;
        case EMErrorNetworkNotConnected:
          NSLog(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
          break;
        case EMErrorServerTimeout:
          NSLog(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
          break;
        default:
          NSLog(NSLocalizedString(@"register.fail", @"Registration failed"));
          break;
      }
    }
  } onQueue:nil];
}

#pragma mark 登录环信账号
- (void)loginEaseMob:(NSString *)userName password:(NSString *)password {
  //异步登陆账号
  [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:userName password:password completion:
   ^(NSDictionary *loginInfo, EMError *error) {
     if (loginInfo && !error) {
       //设置是否自动登录
       [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
       
       //旧数据转换 (如果您的sdk是由2.1.2版本升级过来的，需要家这句话)
       [[EaseMob sharedInstance].chatManager importDataToNewDatabase];
       //获取数据库中数据
       [[EaseMob sharedInstance].chatManager loadDataFromDatabase];
       
       //获取群组列表
       [[EaseMob sharedInstance].chatManager asyncFetchMyGroupsList];
       
       //发送自动登陆状态通知
       [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
       
       //保存最近一次登录用户名
       [self saveLastLoginUsername];
     }else{
       switch (error.errorCode){
         case EMErrorNotFound:
           NSLog(error.description);
           break;
         case EMErrorNetworkNotConnected:
           NSLog(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
           break;
         case EMErrorServerNotReachable:
           NSLog(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
           break;
         case EMErrorServerAuthenticationFailure:
           NSLog(error.description);
           break;
         case EMErrorServerTimeout:
           NSLog(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
           break;
         default:
           NSLog(NSLocalizedString(@"login.fail", @"Login failure"));
           break;
       }
     }
   } onQueue:nil];
  
}

- (void)saveLastLoginUsername{
  NSString *username = [[[EaseMob sharedInstance].chatManager loginInfo] objectForKey:kSDKUsername];
  if (username && username.length > 0) {
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:username forKey:[NSString stringWithFormat:@"em_lastLogin_%@",kSDKUsername]];
    [ud synchronize];
  }
}

- (NSString*)lastLoginUsername{
  NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
  NSString *username = [ud objectForKey:[NSString stringWithFormat:@"em_lastLogin_%@",kSDKUsername]];
  if (username && username.length > 0) {
    return username;
  }
  return nil;
}


@end
